package com.luck.part;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

@Component
@Slf4j
public class LogTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        Long timeSpan = Long.valueOf(config.getValue());
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                long startTime = System.currentTimeMillis();
                return chain.filter(exchange).then(Mono.fromRunnable(()->{
                    long endTime = System.currentTimeMillis();
                    if (endTime - startTime >= timeSpan){
                        URI uri = exchange.getRequest().getURI();
                        log.debug("{},耗时：{}",uri,endTime - startTime);
                    }
                }));
            }
        };
    }
}
